"""@Project -> File   ：python -> 练习
   @IDE    ：PyCharm
   @Author ：PengLinxi
   @Date   ：2021/11/24 11:28
"""


# 16.把scwebsite2_ssl.log日志文件里的ip，时间字段获取出来，时间格式转化为“2021-11-24 12:00:00", 通过ip解析出它属于哪个省份和运营商
# json模块  把字典一样的字符串转化成字典
# 结果写入另一个文件

import requests
import json

f1 = open('scwebsite2_ssl.log', 'r')
f2 = open('获取ip-省份-运营商.txt', 'w')
ip = []
time = []
for line in f1:
    line1 = line.split(" ")
    ip.append(line1[0])
    # str.strip('a'):删除str字符串中的a字符
    time.append(line1[3].strip('['))

    """
# print(time)
for t in time:
    timeArray = time.strptime(t, "%d/%b/%Y:%H:%M:%S")
    timeStamp = int(time.mktime(timeArray))
    new_time = time.strftime("%Y-%m-%d %H:%M:%S", timeStamp)
    new_time.append()
# f2.write(f"ip:{ip},time:{new_time}"+"\n")

"""
f2.write(f"ip:{ip}"+"\n")
f1.close()

for i in ip:
    # url = "http://ip.aliyun.com/outGetIpInfo?accessKey=alibaba-inc&ip=114.119.156.146"
    url = f"http://ip.aliyun.com/outGetIpInfo?accessKey=alibaba-inc&ip={i}"
    response = requests.get(url)
    # print(response.text)
    datajson = json.loads(response.text)
    # print(datajson)
    datajson2 = datajson['data']
    # print(datajson2,type(datajson2))
    region = datajson2['region']
    isp = datajson2['isp']
    f2.write(f"省份：{region}, 运营商：{isp}"+"\n")

f2.close()




